/*
 * @Author: humengchuan 531537052@qq.com
 * @Date: 2024-11-20 10:47:14
 * @LastEditors: humengchuan 531537052@qq.com
 * @LastEditTime: 2024-11-20 15:49:40
 * @FilePath: \project-my\forum-project\utils\redis.js
 * @Description: redis
 */

const redis = require('redis')
const { isProd } = require('./env')


let redisConfig = {
    host: '127.0.0.1',
    port: 6379
}

if (isProd) {
  redisConfig = {
    host: '127.0.0.1',
    port: 6379
  }
}


// 创建客户端
const client = redis.createClient(redisConfig)

client.on('error', (err) => {
    console.log('redis--Error ' + err)
})

client.on('connect', () => {
    console.log('redis--connect')
})

/**
 * 设置key
 * @param {*} key 
 * @param {*} value 
 * @param {*} time 过期时间
 */
const setKey = (key, value, time = 60 * 60) => {
    if (typeof value === 'object') {
        value = JSON.stringify(value)
    }
    client.set(key, value)
    client.expire(key, time)
}

/**
 * 获取key
 * @param {*} key 
 * @returns {Promise}
 */
const getKey = (key) => {
  return new Promise((resolve, reject) => {
    client.get(key, (err, result) => {
      if (err) {
        reject(err)
      } else {
        resolve( JSON.parse(result) )
      }
    })
  })
}

/**
 * 删除key
 * @param {*} key 
 * @returns {Promise}
 */

const delKey = async (key) => {
   await client.del(key)
}

module.exports = {
  setKey,
  getKey,
  delKey
}